package com.maoning.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.maoning.product.service.CategoryBrandRelationService;
import com.maoning.product.vo.Catelog2Vo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Service;

import java.awt.*;
import java.util.*;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.maoning.common.utils.PageUtils;
import com.maoning.common.utils.Query;

import com.maoning.product.dao.CategoryDao;
import com.maoning.product.entity.CategoryEntity;
import com.maoning.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree(Map<String, Object> params) {
        final List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> level1Menus = entities.stream().filter(e -> {
            return e.getParentCid() == 0;
        }).map(menu->{
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1,menu2)->{
            return (menu1.getSort() == null?0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());
        return level1Menus;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root,List<CategoryEntity> all){
        final List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return Objects.equals(categoryEntity.getParentCid(), root.getCatId());
        }).map(categoryEntity -> {
            return categoryEntity.setChildren(getChildrens(categoryEntity, all));
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null?0:menu1.getSort()) - (menu2.getSort() == null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return children;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO: 2021/9/29  在删除之前需要检查一下要删除的内容是否被别人引用了
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 通过一个catelogId找到他的父分类,以此类推,直到把所有父分类id都放进数组,逆序
     * @param catelogId
     * @return
     */
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        final ArrayList<Long> paths = new ArrayList<>();
        findParentPath(catelogId,paths);
        Collections.reverse(paths);

        return paths.toArray(new Long[0]);
    }

    /**
     * 级联更新所有关联的数据
     * @CacheEvict:缓存失效模式的使用
     * 后面的key是表达式,如果写成字符串,要加单引号包起来,不然的话会报错.
     * @param category
     */
    @Transactional
    @Override
//    @CacheEvict(value = "category",key = "'getLevel1Categorys'")
//    如果需要一次性使用多个缓存注解组合,那么使用下面的↓
    @Caching(evict = {
            @CacheEvict(value = "category",key = "'getLevel1Categorys'"),
            @CacheEvict(value = "category",key = "'getCatelogJson'")
    })
//    @CacheEvict(value = "category",allEntries = true)
//    或者使用这个注解加allEntries属性,意思是删除value写的这个分区的全部,所以以后我们尽可能按分区填充缓存数据
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(),category.getName());
    }

    //这个注解表示这个数据会放到缓存,配置文件指定了缓存使用redis.
    @Cacheable(value = {"category"},key = "#root.methodName",sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        System.out.println("getLevel1Categorys去查询了数据库");
        final long l = System.currentTimeMillis();
        final List<CategoryEntity> list = this.list(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        System.out.println("一级菜单耗费的时间: ====> " + (System.currentTimeMillis() - l));
        return list;
    }

    /**
     * 注意:原生的在他下面的getCatelogJson2方法,redisson分布式锁也在下面.因为最后优化成了注解缓存,所以锁没有搬运
     * 向redis查询列表的方法
     * 关于redis的堆外内存溢出问题:
     * 1.原因:是由于springbootstarter-redis依赖的lettuce存在bug(老版本),新的修复了
     * 2.解决方案:可以把springbootstarter-redis中年的lettuce排除,然后加入对应springboot版本的jedis
     * 3.如果使用了以上替换方案,性能可能下降,因为lettuce用了netty,这样他效率会高
     * @return
     */
    @Override
    @Cacheable(value = "category",key = "#root.methodName",sync = true)
    public Map<String, List<Catelog2Vo>> getCatelogJson() {
        Map<String, List<Catelog2Vo>> listMap = null;
        final List<CategoryEntity> list = this.list();

        //1.查出所有1级分类
        final List<CategoryEntity> level1Categorys = getParentCid(list,0L);
        //2.封装数据
        listMap = level1Categorys.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            //1.每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> entities = getParentCid(list,v.getCatId());
            //2.封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (!CollectionUtils.isEmpty(entities)) {
                catelog2Vos = entities.stream().map(l2 -> {
                    final Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.找当前分类的3级分类,封装vo
                    final List<CategoryEntity> level3Catelog = getParentCid(list,l2.getCatId());
                    if (!CollectionUtils.isEmpty(level1Categorys)) {
                        final List<Catelog2Vo.Catelog3Vo> catelog3Vos = level3Catelog.stream().map(l3 -> {
                            //2.封装指定的格式
                            final Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        return listMap;
    }

//    这个方法是用原生实现的,现在我们不需要他了,统一换成使用@cacheable实现↑
    public Map<String, List<Catelog2Vo>> getCatelogJson2(){

        /**
         * 使用redis出现的缓存穿透,雪崩,击穿问题:
         * 穿透:redis为空,数据库也为空.解决:把空结果缓存,设置短暂的过期时间,三五分钟
         * 雪崩:大面积过期.解决:可以给不同的kv设置不同的随机过期时间.
         * 击穿:高频的某几个值时间过期,大量打入数据库.解决:加分布式锁.
         */

        final ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        Map<String, List<Catelog2Vo>> catelogJson = null;
        String catelogJsonStr = opsForValue.get("catelogJson");
        if(StringUtils.isEmpty(catelogJsonStr)){
            //为了防止击穿,在数据库的查询方法是加了本地锁的
            System.out.println("getCatelogJson缓存不命中,去查询数据库");
            try {
                catelogJson = getCatelogJsonFromDbWithRedis();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }else {
            final TypeReference<Map<String, List<Catelog2Vo>>> typeReference = new TypeReference<Map<String, List<Catelog2Vo>>>(){};
            catelogJson = JSON.parseObject(catelogJsonStr, typeReference);
            System.out.println("getCatelogJson缓存命中了,直接返回");
        }
        return catelogJson;
    }

    //使用原生redis实现的分布式锁,结合了lua脚本
    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDbWithRedis() throws InterruptedException {
        //1.加入uuid是为了防止中途处理时间过长,自己的锁失效了,解开了别人的锁
        final String uuid = UUID.randomUUID().toString();
        //没加到锁就循环,加到了就退出循环
        //退出循环就去查数据库
        //解锁的操作放finally,并且使用lua脚本保证原子性
        while (true){
            //保证加锁原子性
            final Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 3, TimeUnit.SECONDS);
            if(lock){
                System.out.println("获取分布式锁成功");
                break;
            }
            System.out.println("获取分布式锁失败,等待重试");
            Thread.sleep(3000);
        }
        Map<String, List<Catelog2Vo>> listMap;
        try {
            listMap = getCatelogJsonFromDb();
        } finally {
            String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                    "    return redis.call(\"del\",KEYS[1])\n" +
                    "else\n" +
                    "    return 0\n" +
                    "end";
            final String lockstr = redisTemplate.opsForValue().get("lock");
            //redis分布式锁原生实现:使用lua脚本保证解锁的原子性
            redisTemplate.execute(new DefaultRedisScript<>(script, Long.class), Arrays.asList("lock"), uuid);
        }

        return listMap;
    }


    /**
     * 向数据库查询商品列表的方法
     * 添加synchronized,锁的是实例对象.
     * 因为spring默认是单例的,所以单服务可以保证锁住
     * 但是多个服务的情况下就不可以了,需要添加分布式锁
     * ==不过其实每个服务放进一个线程来,也还可以接受==但是如果是写入操作就不可以了!
     * @return
     */
    public  Map<String, List<Catelog2Vo>> getCatelogJsonFromDb() {
        /**
         * 将多次的数据库查询变为一次
         */
        //拿到锁以后再查一次redis,查到了就直接返回.
        final String catelogJsonStr = redisTemplate.opsForValue().get("catelogJson");
        Map<String, List<Catelog2Vo>> listMap = null;
        if(!StringUtils.isEmpty(catelogJsonStr)){
            final TypeReference<Map<String, List<Catelog2Vo>>> typeReference = new TypeReference<Map<String, List<Catelog2Vo>>>(){};
            listMap = JSON.parseObject(catelogJsonStr, typeReference);
            System.out.println("FromDb缓存命中,直接返回");
            return listMap;
        }
        //注意如果redis里没有,去查库了.那么需要从库查出来,然后放进redis后,再放锁.
        System.out.println("FromDb查询了数据库");
        final List<CategoryEntity> list = this.list();

        //1.查出所有1级分类
        final List<CategoryEntity> level1Categorys = getParentCid(list,0L);
        //2.封装数据
        listMap = level1Categorys.stream().collect(Collectors.toMap(k -> {
            return k.getCatId().toString();
        }, v -> {
            //1.每一个的一级分类,查到这个一级分类的二级分类
            List<CategoryEntity> entities = getParentCid(list,v.getCatId());
            //2.封装上面的结果
            List<Catelog2Vo> catelog2Vos = null;
            if (!CollectionUtils.isEmpty(entities)) {
                catelog2Vos = entities.stream().map(l2 -> {
                    final Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //1.找当前分类的3级分类,封装vo
                    final List<CategoryEntity> level3Catelog = getParentCid(list,l2.getCatId());
                    if (!CollectionUtils.isEmpty(level1Categorys)) {
                        final List<Catelog2Vo.Catelog3Vo> catelog3Vos = level3Catelog.stream().map(l3 -> {
                            //2.封装指定的格式
                            final Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(catelog3Vos);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        redisTemplate.opsForValue().set("catelogJson", JSON.toJSONString(listMap),1, TimeUnit.DAYS);
        return listMap;
    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> list,Long catId) {
        return list.stream().filter(item -> item.getParentCid().equals(catId)).collect(Collectors.toList());
    }

    private void findParentPath(Long catelogId, ArrayList<Long> paths) {
        paths.add(catelogId);
        final CategoryEntity byId = getById(catelogId);
        if(byId.getParentCid() != 0){
            findParentPath(byId.getParentCid(),paths);
        }
    }

}